<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="dialogVisible" @close="handleClose">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      ref="deptForm"
      label-width="120px"
      :model="formData"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="handleFocus"
        >
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button
          type="primary"
          size="small"
          @click="handleSubmit"
        >确定</el-button>
        <el-button size="small" @click="handleClose">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import { getDepartmentsAPI, addDepartmentsAPI, updateDepartmentsAPI } from '@/api/departments'
import { getEmployeeSimpleAPI } from '@/api/employees'
export default {
  props: {
    dialogVisible: Boolean,
    currentNode: {
      type: Object,
      default: () => ({})
    }
  },
  // - 部门名称（name）：必填 1-50个字符  / 同级部门中禁止出现重复部门
  // - 部门编码（code）：必填 1-50个字符  / 部门编码在整个模块中都不允许重复
  // - 部门负责人（manager）：必填
  // - 部门介绍 ( introduce)：必填 1-300个字符
  data() {
    const checkCode = async(rules, value, callback) => {
      // console.log(rules, value)
      const { depts } = await getDepartmentsAPI()
      console.log(depts)
      let flag = false
      if (this.formData.id) {
        flag = depts.some(item => item.id !== this.currentNode.id && item.code === value)
      } else {
        flag = depts.some(item => {
          return item.code === value
        })
      }
      flag ? callback(new Error(`部门代码${value}重复，重新输入`)) : callback()
    }
    const checkName = async(rules, value, callback) => {
      const { depts } = await getDepartmentsAPI()
      let flag = false
      // console.log(rules, value)
      if (this.formData.id) {
        const list = depts.filter(item => item.pid === this.forData.pid && item.id !== this.formData.id)
        console.log(list)
        flag = list.some(item => item.name === value)
      } else {
        const list = depts.filter(item => item.id === this.currentNode.id)
        flag = list.some(item => {
          return item.name === value
        })
      }

      flag ? callback(new Error(`部门名称${value}重复，重新输入`)) : callback()
    }
    return {
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [{ required: true, message: '部门名称必填', trigger: 'blur' },
          { min: 1, max: 50, trigger: 'blur' }, { validator: checkName, trigger: 'blur' }],
        code: [{ required: true, message: '部门编码必填', trigger: 'blur' },
          { min: 1, max: 50, trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }],
        manager: [{ required: true, message: '部门负责人必填' }],
        introduce: [{ required: true, message: '部门介绍必填', trigger: 'blur' }, { min: 1, max: 300, trigger: 'blur' }]
      },
      peoples: []
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:dialogVisible', false)
      this.$refs.deptForm.resetFields()
      this.formData = {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      }
    },
    async handleFocus() {
      const res = await getEmployeeSimpleAPI()
      console.log('people', res)
      this.peoples = res
    },
    async handleSubmit() {
      try {
        await this.$refs.deptForm.validate()
        this.formData.id ? await updateDepartmentsAPI(this.formData)
          : await addDepartmentsAPI({ ...this.formData, pid: this.currentNode.id })
        this.$message.success(`部门${!this.formData.id ? '新增' : '编辑'}成功`)
        this.handleClose()
        this.$parent.getDepartments()
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>
</style>
